package com.kfh.ybracelet.location;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.adapter.ChooseOneAdapter;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.Child;
import com.kfh.ybracelet.bean.ChildAndWatchInforResult;
import com.kfh.ybracelet.my.AddBabyActivity;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.DensityUtil;
import com.kfh.ybracelet.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 定位模块 选择老人页面
 * Created by Aaron on 15/7/30.
 */
public class ChooseLocationBabyActivity extends BaseActivity {

    private ChooseOneAdapter chooseOneAdapter;
    private SwipeMenuListView gv_baby;
    private List<Child> datas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_one_choose_baby);

        datas = new ArrayList<>();

        initWidget();

        //获取孩子列表
        getChildList(null);
    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        TextView tv_right = (TextView) findViewById(R.id.tv_right);

        tv_title.setText(getResources().getString(R.string.choose_baby));
        tv_right.setText(getResources().getString(R.string.add));

        gv_baby = (SwipeMenuListView) findViewById(R.id.gv_baby);

        iv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);

        chooseOneAdapter = new ChooseOneAdapter(this, datas);
        gv_baby.setAdapter(chooseOneAdapter);

        gv_baby.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (datas == null)
                    return;

                if (datas.size() == 0) {
                    showToast(getResources().getString(R.string.please_choose_old_first));
                    return;
                }

                //通知定位页面切换了宝宝
                EventBus.getDefault().post(!sp.getString(Constant.CURRENTCHILDID, "").equals(datas.get(position).id));

                SharedPreferences.Editor edit = sp.edit();
                edit.putString(Constant.CURRENTCHILDID, datas.get(position).id);
                edit.putString(Constant.CURRENTCHILDNAME, datas.get(position).name);
                edit.putInt(Constant.LEVEL, datas.get(position).level);
                edit.apply();

                finish();

            }
        });

        //滑动删除
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());

                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));

                deleteItem.setWidth(DensityUtil.dip2px(ChooseLocationBabyActivity.this, 80));

                deleteItem.setIcon(R.mipmap.ic_delete);

                menu.addMenuItem(deleteItem);

            }
        };

        gv_baby.setMenuCreator(creator);

        gv_baby.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:// delete

                        if (datas == null || datas.size() < 1) {
                            return false;
                        }

                        new AlertDialog.Builder(ChooseLocationBabyActivity.this).setTitle("提醒").setMessage("是否要删除" + datas.get(position).name)
                                .setNegativeButton("取消", null).setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                delArea(datas.get(position).id);
                            }
                        }).show();

                        break;
                }
                return false;
            }
        });
    }

    //删除老人
    private void delArea(final String itemId) {

        JSONObject j = new JSONObject();

        j.put("id", itemId);
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("加载中...", this, Constant.WEB_ROOT + Constant.DELCHILD, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            org.json.JSONObject j = new org.json.JSONObject(str);

//                            if (j.getInt("code") == Constant.STATUS_SUCCESS) {

                                showToast("删除成功");

                                //判断当前选择的 是否是删除掉的这个
                                getChildList(itemId);

//                            } else {
//                                showToast(Constant.showErrorMsg(j.getInt("code"), ChooseLocationBabyActivity.this));
//                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);

    }

    /**
     * 获取孩子列表
     */
    private void getChildList(final String itemId) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest(getResources().getString(R.string.getting_old_list), this, Constant.WEB_ROOT + Constant.GETCHILDERNANDWATCH,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            ChildAndWatchInforResult request = JSONObject.parseObject(str, ChildAndWatchInforResult.class);

//                            if (request.code == Constant.STATUS_SUCCESS) {

                                datas = request.data;

                                if (datas == null) {
                                    showToast(getResources().getString(R.string.please_bind_old_first));
                                    return;
                                }

                                if (datas.size() == 0) {

                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString(Constant.CURRENTCHILDID, "");
                                    edit.putString(Constant.CURRENTCHILDNAME, "");
                                    edit.putInt(Constant.LEVEL, 0);
                                    edit.apply();

                                    Intent mIntent = new Intent(ChooseLocationBabyActivity.this, AddBabyActivity.class);
                                    mIntent.putExtra("cancle", false);
                                    startActivity(mIntent);
                                    return;
                                }

                                if (sp.getString(Constant.CURRENTCHILDID, "").equals(itemId)) {

                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString(Constant.CURRENTCHILDID, datas.get(0).id);
                                    edit.putString(Constant.CURRENTCHILDNAME, datas.get(0).name);
                                    edit.putInt(Constant.LEVEL, datas.get(0).level);
                                    edit.apply();

                                    EventBus.getDefault().post(true);

                                }

                                chooseOneAdapter = new ChooseOneAdapter(ChooseLocationBabyActivity.this, datas);

                                gv_baby.setAdapter(chooseOneAdapter);

//                            } else {
//                                showToast(Constant.showErrorMsg(request.code, ChooseLocationBabyActivity.this));
//                            }

                        } catch (Exception e) {

                            showToast(Constant.NODATA);
                            e.printStackTrace();
                            LogUtil.e("TAG", "获取学校孩子联系人数据解析错误");

                        }
                    }
                }, null);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {

            case R.id.iv_left:

                finish();

                break;

            case R.id.tv_right://添加老人

                Intent mIntent = new Intent(this, AddBabyActivity.class);
                startActivity(mIntent);

                break;

        }

    }

}
